package com.ys.service.overseas.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ys.config.MenuId;
import com.ys.dto.AddDto;
import com.ys.entity.base.TsBatchImportInfo;
import com.ys.entity.base.TsBatchImportLog;
import com.ys.entity.overseas.TosChannelStock;
import com.ys.entity.overseas.TosPlatformInformation;
import com.ys.entity.overseas.TosProductActive;
import com.ys.entity.overseas.TosProductBasis;
import com.ys.entity.sys.TsUserChange;
import com.ys.entity.sys.YsCol;
import com.ys.enume.base.TsBatchImportLogEnum;
import com.ys.mapper.base.BaseDiyMapper;
import com.ys.mapper.base.TsBatchImportInfoMapper;
import com.ys.mapper.base.TsBatchImportLogMapper;
import com.ys.mapper.overseas.OverseasMapper;
import com.ys.mapper.overseas.TosChannelStockMapper;
import com.ys.mapper.overseas.TosProductActiveMapper;
import com.ys.mapper.overseas.TosProductBasisMapper;
import com.ys.service.base.TsBatchImportLogService;
import com.ys.service.overseas.TosProductBasisService;
import com.ys.service.sys.CommonApiService;
import com.ys.util.CheckUtil;
import com.ys.util.FileUtilYs;
import com.ys.util.baidu.ApiHttpClientUtils;
import com.ys.util.shiro.ShiroUtils;
import com.ys.vo.R;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.io.*;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
 * HW商品库
 */
@Service("tosProductBasisService")
public class TosProductBasisServiceImpl implements TosProductBasisService {
	private static final Logger logger = LoggerFactory.getLogger(TosProductBasisServiceImpl.class);

	@Autowired
	private TosProductBasisMapper tosProductBasisMapper;

	@Autowired
	private TosChannelStockMapper tosChannelStockMapper;

	@Autowired
	private TosProductActiveMapper tosProductActiveMapper;

	@Autowired
	private OverseasMapper overseasMapper;

	@Autowired
	private CheckUtil checkUtil;

	@Autowired
	private CommonApiService<TosProductBasis> commonApiService;

	@Autowired
	private ApiHttpClientUtils apiHttpUtils;

	@Autowired
	private BaseDiyMapper baseDiyMapper;

	@Autowired
	private TsBatchImportLogMapper tsBatchImportLogMapper;

	@Autowired
	private TsBatchImportInfoMapper tsBatchImportInfoMapper;

	@Autowired
	private TsBatchImportLogService tsBatchImportLogService;


	private long menuId = MenuId.TOS_ProductBasis;
	//@Autowired
	//private HttpUtilYs httpUtilYs;



	/**
	 * 新增
	 */
	@Override
	@Transactional(timeout=120,propagation= Propagation.REQUIRES_NEW)
	public R add(Map<String, Object> params, Long menuId) throws Exception{
		logger.info("新增传参:"+params);
		//参数验证
		String errorBack = checkParams(params, menuId);
		if(errorBack!=null && !"".equals(errorBack)){
			return R.error(errorBack);
		}
		TosProductBasis entity = JSON.parseObject(JSON.toJSONString(params), TosProductBasis.class);
		//entity.setStatus(1);//状态

		//获取制单人信息
		TsUserChange tsUserChange = new TsUserChange().setUserId(ShiroUtils.getUserId()).setStatus(1).queryFirst();
		if(tsUserChange!=null){
			entity.setCreateChangeId(tsUserChange.getId());//制单人变更信息
		}else {
			return R.error("未查询到制单人信息！");
		}
		//验证标识编码 + 渠道唯一
		int checkSame = new TosProductBasis().setPlatformId(entity.getPlatformId()).setSignCode(entity.getSignCode()).count();
		if(checkSame>0){
			return R.error("标识编码 + 渠道必须唯一！");
		}

		//验证母体编码是否存在
		/*
		if(checkUtil.isNotNullByObject(entity.getFromCode())){
			int checkFromCode =new TosProductBasis().setCode(entity.getFromCode()).count();
			if(checkFromCode<=0){
				return R.error("母体编码不存在！");
			}
		}
		 */

		if("setNewCode".equals(entity.getCode())){
			//生成商品编码
			String code = commonApiService.getCommonNextUkey(menuId,"Code");
			entity.setCode(code);
		}else {
			//验证商品编码唯一
			int checkSameCode = new TosProductBasis().setCode(entity.getCode()).count();
			if(checkSameCode>0){
				//若有其他相同的商品编码，则重新生成一个
				String code = commonApiService.getCommonNextUkey(menuId,"Code");
				entity.setCode(code);
			}
		}


		//计算
		entity = count(entity);
		//新增HW商品库
		tosProductBasisMapper.insert(entity);

		int stockNum = checkUtil.isNotNullByObject(params.get("stockNum"))? Integer.parseInt(params.get("stockNum").toString()) : 0;
		//新增HW商品渠道库存
		TosChannelStock tosChannelStock = new TosChannelStock()
				.setProductCode(entity.getCode())
				.setStockNum(stockNum)//库存数量
				.setStatus(1);
		tosChannelStockMapper.insert(tosChannelStock);

		//新增HW商品listing库
		TosProductActive tosProductActive = new TosProductActive()
				.setProductCode(entity.getCode())
				.setAnnexFile("0个附件")
				.setStatus(1);
		tosProductActiveMapper.insert(tosProductActive);

		return R.ok(AddDto.gotoEdit("/web/overseas/tosProductBasis/toEdit?id=" + entity.getId()));
	}

	/**
	 * 修改
	 */
	@Override
	@Transactional(timeout=120,propagation= Propagation.REQUIRES_NEW)
	public R update(Map<String, Object> params, Long menuId) throws Exception{
		logger.info("修改传参:"+params);
		//参数验证
		String errorBack = checkParams(params, menuId);
		if(errorBack!=null && !"".equals(errorBack)){
			return R.error(errorBack);
		}
		TosProductBasis entity = JSON.parseObject(JSON.toJSONString(params), TosProductBasis.class);
		//计算
		entity = count(entity);
		//修改HW商品库
		tosProductBasisMapper.update(entity);

		//修改HW商品渠道库存数量，根据商品编码
		overseasMapper.updateTosChannelStockStockNumByCode(
				entity.getCode(),
				(params.get("stockNum")!=null ? Integer.parseInt(params.get("stockNum").toString()) : 0)
		);
		return R.ok(AddDto.gotoEdit("/web/overseas/tosProductBasis/toEdit?id=" + entity.getId()));
	}

	//计算
	public TosProductBasis count(TosProductBasis entity)throws Exception{
		BigDecimal suggestAmount = entity.getSuggestAmount();// 商品建议价格
		BigDecimal purchaseAmount = entity.getPurchaseAmount();// 商品采购价
		BigDecimal deliveryAmount = entity.getDeliveryAmount();// 商品配送价

		//商品利润 = 商品建议价格-商品采购价-商品配送价
		BigDecimal profitAmount = suggestAmount.subtract(purchaseAmount).subtract(deliveryAmount);
		entity.setProfitAmount(profitAmount.setScale(2, RoundingMode.HALF_UP));

		//利润率 = 商品利润/（商品采购价+商品配送价）
		BigDecimal profitRatio = profitAmount.divide((purchaseAmount.add(deliveryAmount)), 2, RoundingMode.HALF_UP);
		entity.setProfitRatio(profitRatio);
		return entity;
	}

	/**
	 * 参数验证
	 */
	public String checkParams(Map<String, Object> params, Long menuId) throws Exception {
		//获取pc字段数据
		List<YsCol> listField = new YsCol()
				.where("A.MenuId = "+menuId)
				.setOrderby("A.SortNo ASC")
				.queryList();
		//验证必填字段的非空；其他字段的长度限制、类型
		String backMsg = checkUtil.checkTableColLengthAndDataType("TOS_ProductBasis",listField,params,ysColItem->ysColItem.getFormEditRequired()!=null && ysColItem.getFormEditRequired() == 1);

		return backMsg;
	}


	//获取列表数据
	@Override
	public Map<String,Object> getExtraParam( Long id) throws Exception{
		return new TosProductBasis()

				.addLeftJoin("TS_UserChange U ON U.Id = A.CreateChangeId ")
				.addField("U.UserId + '/' + U.UserName AS _ys_createUserName")//制单人
				.addField("U.DeptName AS deptName")//部门
				.addField("U.RoleName AS roleName")//岗位

				.addLeftJoin("TOS_ChannelStock B ON B.ProductCode = A.Code ")//HW商品库存表
				.addField("B.StockNum AS stockNum")//商品库存数量
				.addField("FORMAT(B.UpdateTime, 'yyyy-MM-dd HH:mm:ss') AS dataTime")//数据时间

				.addLeftJoin("TOS_PlatformInformation C ON C.Id = A.PlatformId ")//平台信息维护表
				.addField("C.HwChannel AS hwChannel")//渠道
				.addField("C.PlatformCode AS platformCode")//平台
				.addField("C.HwName AS hwName")//区域
				.addField("C.RegionName AS regionName")//站点
				.addField("C.CurrencyCode AS currencyCode")//币种

				.setId(id)
				.queryFirstMap();
	}


	/**
	 * 批量导入
	 */
	@Override
	public R importInfo(String rows, Long menuId){
		try {
			List<TsBatchImportLog> list = new ArrayList<>();
			String userId = ShiroUtils.getUserId();
			//获取导入数据
			JSONArray detailList = JSON.parseArray(rows);
			for(int i=0;i<detailList.size();i++){
				JSONObject info = detailList.getJSONObject(i);
				if(info!=null){
					TsBatchImportLog tsBatchImportLog = new TsBatchImportLog();
					tsBatchImportLog.setUserId(userId);
					tsBatchImportLog.setImportInfo(info.toJSONString());
					tsBatchImportLog.setInfoType(TsBatchImportLogEnum.InfoType.TOS_ProductBasis.value);
					tsBatchImportLog.setImportState(TsBatchImportLogEnum.ImportState.NO.value);
					tsBatchImportLog.setStatus(0);
					list.add(tsBatchImportLog);
				}
			}
			if(list.size()>0){
				baseDiyMapper.insertBatchTsBatchImportLog(list);
			}
		}catch (Exception e){
			logger.error("导入出错：",e.getMessage(),e);
			return R.error("导入出错,请稍后重试!");
		}
		return R.ok("请点击“导入详情”按钮查看导入进度！");
	}


	@Override
	public void importInfoFromBatchImportLogByUser(){
		TsBatchImportInfo tsBatchImportInfo = new TsBatchImportInfo()
				.setStatus(1)
				.setImportInfoState(0)
				.setUserId(ShiroUtils.getUserId())
				.setInfoType(TsBatchImportLogEnum.InfoType.TOS_ProductBasis.value)
				;
		tsBatchImportInfoMapper.insert(tsBatchImportInfo);
		baseDiyMapper.updateTsBatchImportLogInfo(ShiroUtils.getUserId(), TsBatchImportLogEnum.InfoType.TOS_ProductBasis.value, tsBatchImportInfo.getId());

		List<TsBatchImportLog> logList = new TsBatchImportLog()
				.setPid(tsBatchImportInfo.getId())
				.setUserId(ShiroUtils.getUserId())
				.setInfoType(TsBatchImportLogEnum.InfoType.TOS_ProductBasis.value)
				.setImportState(TsBatchImportLogEnum.ImportState.NO.value)
				.queryList();
		if(logList!=null && logList.size()>0){
			for(TsBatchImportLog tsBatchImportLog:logList){
				addByOne(tsBatchImportLog);
			}
		}
		int importInfoState = 1;
		int count = new TsBatchImportLog().setPid(tsBatchImportInfo.getId()).setImportState(TsBatchImportLogEnum.ImportState.FAIL.value).count();
		if(count>0){
			importInfoState = 2;
		}
		TsBatchImportInfo infoByUpdate = new TsBatchImportInfo().setId(tsBatchImportInfo.getId()).setImportInfoState(importInfoState);
		tsBatchImportInfoMapper.update(infoByUpdate);
	}

	//新增商品库信息
	public void addByOne(TsBatchImportLog tsBatchImportLog){
		try {
			String importInfo = tsBatchImportLog.getImportInfo();
			JSONObject info = JSONObject.parseObject(importInfo);
			Map<String, Object> infoMap = new HashMap<>();
			for (String key : info.keySet()) {
				infoMap.put(key, info.get(key)!=null?info.get(key).toString().trim():info.get(key));
			}

			StringBuilder errorMsg = new StringBuilder();
			//验证渠道
			if(info.get("hwChannel")==null || "".equals(info.get("hwChannel"))){
				errorMsg.append("数据渠道为空；");
			}
			//验证平台
			if(info.get("platformCode")==null || "".equals(info.get("platformCode"))){
				errorMsg.append("平台为空；");
			}
			//验证区域
			if(info.get("hwName")==null || "".equals(info.get("hwName"))){
				errorMsg.append("区域为空；");
			}
			//验证站点
			if(info.get("regionName")==null || "".equals(info.get("regionName"))){
				errorMsg.append("站点为空；");
			}
			//验证币种
			if(info.get("currencyCode")==null || "".equals(info.get("currencyCode"))){
				errorMsg.append("币种为空；");
			}
			if(errorMsg.length()<=0){
				TosPlatformInformation tosPlatformInformation = new TosPlatformInformation()
						.setHwChannel(info.get("hwChannel").toString().trim())//渠道
						.setPlatformCode(info.get("platformCode").toString().trim())//平台
						.setHwName(info.get("hwName").toString().trim())//区域名称
						.setRegionName(info.get("regionName").toString().trim())//站点
						.setCurrencyCode(info.get("currencyCode").toString().trim())//币种
						.setStatus(1)
						.queryFirst();

				if(tosPlatformInformation!=null && tosPlatformInformation.getId()!=null){
					infoMap.put("platformId",tosPlatformInformation.getId());
				}else {
					errorMsg.append("未在渠道管理中查询到对应的渠道信息；");
				}
			}

			//错误信息
			if(errorMsg.length()>0){
				tsBatchImportLogService.updateErrorReason(tsBatchImportLog,errorMsg.toString());
				return;
			}
			infoMap.put("status",1);


			//参数验证
			String errorBack = checkParams(infoMap, menuId);
			if(errorBack!=null && !"".equals(errorBack)){
				tsBatchImportLogService.updateErrorReason(tsBatchImportLog,errorBack);
				return;
			}

			try {
				//商品图片上传文件服务器
				if(checkUtil.isNotNullByObject(info.get("productImg"))){
					String imgPath = info.get("productImg").toString();
					String[] parts = StringUtils.split(imgPath, "?");
					R res = FileUtilYs.uploadFileByUrl(parts[0]);
					infoMap.put("productImg",res.get("data"));
				}
			}catch (IOException e){
				logger.error("上传文件出错：",e.getMessage(),e);
				tsBatchImportLogService.updateErrorReason(tsBatchImportLog,e.getMessage());
				return;
			}


			TosProductBasis entity = JSON.parseObject(JSON.toJSONString(infoMap), TosProductBasis.class);
			entity.setStatus(1);//状态

			//获取制单人信息
			TsUserChange tsUserChange = new TsUserChange().setUserId(ShiroUtils.getUserId()).setStatus(1).queryFirst();
			if(tsUserChange!=null){
				entity.setCreateChangeId(tsUserChange.getId());//制单人变更信息
			}else {
				tsBatchImportLogService.updateErrorReason(tsBatchImportLog,"未查询到制单人信息；");
				return;
			}
			//验证标识编码 + 渠道唯一
			int checkSame = new TosProductBasis().setPlatformId(entity.getPlatformId()).setSignCode(entity.getSignCode()).count();
			if(checkSame>0){
				tsBatchImportLogService.updateErrorReason(tsBatchImportLog,"标识编码 + 渠道必须唯一；");
				return;
			}
			//生成商品编码
			String code = commonApiService.getCommonNextUkey(menuId,"Code");
			entity.setCode(code);

			//计算
			entity = count(entity);
			//新增HW商品库
			tosProductBasisMapper.insert(entity);

			int stockNum = checkUtil.isNotNullByObject(infoMap.get("stockNum"))? Integer.parseInt(infoMap.get("stockNum").toString()) : 0;
			//新增HW商品渠道库存
			TosChannelStock tosChannelStock = new TosChannelStock()
					.setProductCode(entity.getCode())
					.setStockNum(stockNum)//库存数量
					.setStatus(1);
			tosChannelStockMapper.insert(tosChannelStock);

			//新增HW商品listing库
			TosProductActive tosProductActive = new TosProductActive()
					.setProductCode(entity.getCode())
					.setAnnexFile("0个附件")
					.setStatus(1);
			tosProductActiveMapper.insert(tosProductActive);

			//修改成功标识
			TsBatchImportLog logByUpdate = new TsBatchImportLog();
			logByUpdate.setId(tsBatchImportLog.getId());
			logByUpdate.setImportState(TsBatchImportLogEnum.ImportState.SUCCESS.value);
			tsBatchImportLogMapper.update(logByUpdate);

		}catch (Exception e){
			logger.error("导入出错：",e.getMessage(),e);
			tsBatchImportLogService.updateErrorReason(tsBatchImportLog,e.getMessage());
		}

	}




	/**
	 * 批量导入
	 */
	//@Override
	/*
	public R importInfoFromBatchImportLog(String rows, Long menuId){
		logger.info("HW商品库导入的数据：\n"+rows);
		try {
			StringBuilder errorMsg = new StringBuilder();
			//获取导入数据
			JSONArray detailList = JSON.parseArray(rows);
			for(int i=0;i<detailList.size();i++){
				JSONObject info = detailList.getJSONObject(i);
				Map<String, Object> infoMap = new HashMap<>();
				for (String key : info.keySet()) {
					infoMap.put(key, info.get(key)!=null?info.get(key).toString().trim():info.get(key));
				}

				//验证渠道
				if(info.get("hwChannel")==null || "".equals(info.get("hwChannel"))){
					logger.error("第"+(i+1)+"条数据渠道为空");
					errorMsg.append("第"+(i+1)+"条数据渠道为空\n");
					continue;
				}
				//验证平台
				if(info.get("platformCode")==null || "".equals(info.get("platformCode"))){
					logger.error("第"+(i+1)+"条数据平台为空");
					errorMsg.append("第"+(i+1)+"条数据平台为空\n");
					continue;
				}
				//验证区域
				if(info.get("hwName")==null || "".equals(info.get("hwName"))){
					logger.error("第"+(i+1)+"条数据区域为空");
					errorMsg.append("第"+(i+1)+"条数据区域为空\n");
					continue;
				}
				//验证站点
				if(info.get("regionName")==null || "".equals(info.get("regionName"))){
					logger.error("第"+(i+1)+"条数据站点为空");
					errorMsg.append("第"+(i+1)+"条数据站点为空\n");
					continue;
				}
				//验证币种
				if(info.get("currencyCode")==null || "".equals(info.get("currencyCode"))){
					logger.error("第"+(i+1)+"条数据币种为空");
					errorMsg.append("第"+(i+1)+"条数据币种为空\n");
					continue;
				}

				TosPlatformInformation tosPlatformInformation = new TosPlatformInformation()
						.setHwChannel(info.get("hwChannel").toString().trim())//渠道
						.setPlatformCode(info.get("platformCode").toString().trim())//平台
						.setHwName(info.get("hwName").toString().trim())//区域名称
						.setRegionName(info.get("regionName").toString().trim())//站点
						.setCurrencyCode(info.get("currencyCode").toString().trim())//币种
						.setStatus(1)
						.queryFirst();

				if(tosPlatformInformation!=null && tosPlatformInformation.getId()!=null){
					infoMap.put("platformId",tosPlatformInformation.getId());
				}else {
					errorMsg.append("第"+(i+1)+"条数据，未查询到对应的渠道信息\n");
					continue;
				}
				//生成商品编码
				//String code = commonApiService.getCommonNextUkey(menuId,"Code");
				infoMap.put("status",1);
				infoMap.put("code","setNewCode");

				//商品图片上传文件服务器
				if(checkUtil.isNotNullByObject(info.get("productImg"))){
					String imgPath = info.get("productImg").toString();
					String[] parts = StringUtils.split(imgPath, "?");
					R res = FileUtilYs.uploadFileByUrl(parts[0]);
					infoMap.put("productImg",res.get("data"));
				}


				//新增
				R res = add(infoMap, menuId);
				if(!res.getCode().equals(R.Code.SUCCESS.value)){
					errorMsg.append(res.getMsg());
				}
			}

			if(errorMsg.length()>0){
				return R.ok(errorMsg.toString());
			}

		}catch (IOException e){
			logger.error("导入出错：",e.getMessage(),e);
			return R.error("导入出错,图片文件路径有误!");
		}catch (Exception e){
			logger.error("导入出错：",e.getMessage(),e);
			return R.error("导入出错,请稍后重试!");
		}


		return R.ok("导入成功！");
	}

	 */





}
